<template>
  <div class="profile-page">
    <NavBar />
    
    <div class="main-content">
      <div class="container">
        <div class="profile-header">
          <div class="user-info">
            <el-avatar :src="userStore.user?.avatar_url" :size="80">
              {{ userStore.user?.username?.charAt(0).toUpperCase() }}
            </el-avatar>
            <div class="user-details">
              <h1 class="username">{{ userStore.user?.username }}</h1>
              <p class="user-bio" v-if="userStore.user?.bio">{{ userStore.user.bio }}</p>
              <p class="user-email">{{ userStore.user?.email }}</p>
            </div>
          </div>
          
          <div class="profile-actions">
            <el-button @click="editProfile">
              <el-icon><Edit /></el-icon>
              编辑资料
            </el-button>
          </div>
        </div>
        
        <div class="profile-content">
          <el-tabs v-model="activeTab" class="profile-tabs">
            <el-tab-pane label="个人设置" name="settings">
              <div class="settings-section">
                <h3>个人设置</h3>
                
                <el-form
                  ref="settingsFormRef"
                  :model="settingsForm"
                  :rules="settingsRules"
                  label-width="100px"
                  class="settings-form"
                >
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="settingsForm.username" />
                  </el-form-item>
                  
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="settingsForm.email" />
                  </el-form-item>
                  
                  <el-form-item label="姓名" prop="full_name">
                    <el-input v-model="settingsForm.full_name" />
                  </el-form-item>
                  
                  <el-form-item label="个人简介" prop="bio">
                    <el-input
                      v-model="settingsForm.bio"
                      type="textarea"
                      :rows="3"
                      maxlength="500"
                      show-word-limit
                    />
                  </el-form-item>
                  
                  <el-form-item label="头像" prop="avatar_url">
                    <div class="avatar-upload-section">
                      <div class="avatar-preview">
                        <el-avatar :src="settingsForm.avatar_url" :size="80">
                          {{ settingsForm.username?.charAt(0).toUpperCase() }}
                        </el-avatar>
                        <p class="avatar-preview-text">当前头像</p>
                      </div>
                      
                      <div class="avatar-upload-options">
                        <div class="upload-buttons">
                          <el-upload
                            ref="uploadRef"
                            :auto-upload="false"
                            :show-file-list="false"
                            :on-change="handleAvatarChange"
                            :before-upload="beforeAvatarUpload"
                            accept="image/*"
                            class="avatar-uploader"
                          >
                            <el-button type="primary" :loading="uploadingAvatar">
                              <el-icon><Upload /></el-icon>
                              上传并裁剪
                            </el-button>
                          </el-upload>
                          
                          <el-button 
                            type="success" 
                            @click="handleDirectUpload"
                            :loading="uploadingAvatar"
                          >
                            <el-icon><Upload /></el-icon>
                            直接上传
                          </el-button>
                        </div>
                        
                        <div class="avatar-url-input">
                          <el-input 
                            v-model="settingsForm.avatar_url" 
                            placeholder="或输入头像图片URL" 
                            @input="handleAvatarUrlChange"
                          />
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                  
                  <el-form-item>
                    <el-button type="primary" @click="updateSettings" :loading="updating">
                      保存设置
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>

    <Footer />
    
    <!-- 头像裁剪组件 -->
    <AvatarCropper 
      :model-value="showCropper"
      @update:model-value="showCropper = $event"
      :image-url="cropperImageUrl"
      @cropped="handleCropped"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage, type FormInstance, type FormRules, type UploadProps, type UploadUserFile } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import NavBar from '@/components/NavBar.vue'
import Footer from '@/components/Footer.vue'
import AvatarCropper from '@/components/AvatarCropper.vue'
import type { UserUpdate } from '@/types'
import api from '@/utils/api'

const router = useRouter()
const userStore = useUserStore()

const activeTab = ref('settings')
const updating = ref(false)
const uploadingAvatar = ref(false)
const showCropper = ref(false)
const cropperImageUrl = ref('')

const settingsFormRef = ref<FormInstance>()
const uploadRef = ref()

const settingsForm = reactive<UserUpdate>({
  username: '',
  email: '',
  full_name: '',
  bio: '',
  avatar_url: ''
})

const settingsRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}


const editProfile = () => {
  activeTab.value = 'settings'
}

const updateSettings = async () => {
  if (!settingsFormRef.value) return
  
  try {
    await settingsFormRef.value.validate()
    updating.value = true
    
    await userStore.updateUser(settingsForm)
    ElMessage.success('设置更新成功')
  } catch (error) {
    console.error('更新设置失败:', error)
} finally {
    updating.value = false
  }
}

// 头像上传相关函数
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  
  return true
}

const handleAvatarChange = async (file: UploadUserFile) => {
  if (!file.raw) return
  
  // 创建图片URL用于裁剪
  const imageUrl = URL.createObjectURL(file.raw)
  cropperImageUrl.value = imageUrl
  showCropper.value = true
}

const handleDirectUpload = () => {
  // 创建隐藏的文件输入
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.style.display = 'none'
  
  input.onchange = async (event) => {
    const file = (event.target as HTMLInputElement).files?.[0]
    if (!file) return
    
    // 验证文件
    if (!beforeAvatarUpload(file)) return
    
    try {
      uploadingAvatar.value = true
      
      // 创建FormData
      const formData = new FormData()
      formData.append('file', file)
      
      // 上传图片
      const response = await api.post('/posts/upload-image', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      
      // 更新头像URL
      settingsForm.avatar_url = response.data.url
      ElMessage.success('头像上传成功')
    } catch (error) {
      console.error('头像上传失败:', error)
      ElMessage.error('头像上传失败，请重试')
    } finally {
      uploadingAvatar.value = false
    }
  }
  
  // 触发文件选择
  document.body.appendChild(input)
  input.click()
  document.body.removeChild(input)
}

const handleCropped = (url: string) => {
  settingsForm.avatar_url = url
  showCropper.value = false
  cropperImageUrl.value = ''
}

const handleAvatarUrlChange = () => {
  // URL输入时的处理，可以添加URL验证
  // 这里暂时不需要特殊处理
}


onMounted(() => {
  // 初始化设置表单
  if (userStore.user) {
    settingsForm.username = userStore.user.username
    settingsForm.email = userStore.user.email
    settingsForm.full_name = userStore.user.full_name || ''
    settingsForm.bio = userStore.user.bio || ''
    settingsForm.avatar_url = userStore.user.avatar_url || ''
  }
  
})
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding: 2rem 0;
  background: #f5f7fa;
}

.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

.profile-header {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.username {
  font-size: 1.5rem;
  font-weight: 700;
  color: #333;
  margin: 0;
}

.user-bio {
  color: #666;
  margin: 0;
}

.user-email {
  color: #999;
  font-size: 0.875rem;
  margin: 0;
}

.profile-content {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.profile-tabs {
  margin-top: 1rem;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.section-header h3 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.empty-state {
  text-align: center;
  padding: 3rem 0;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.post-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  transition: all 0.3s;
}

.post-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.post-info {
  flex: 1;
}

.post-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: #333;
  margin: 0 0 0.5rem 0;
}

.post-excerpt {
  color: #666;
  margin: 0 0 0.5rem 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-meta {
  display: flex;
  gap: 1rem;
  font-size: 0.875rem;
  color: #999;
}

.post-stats {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.post-actions {
  display: flex;
  gap: 0.5rem;
}

.settings-section h3 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #333;
  margin: 0 0 1.5rem 0;
}

.settings-form {
  max-width: 500px;
}

.avatar-upload-section {
  display: flex;
  gap: 2rem;
  align-items: flex-start;
}

.avatar-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
}

.avatar-preview-text {
  font-size: 0.875rem;
  color: #666;
  margin: 0;
}

.avatar-upload-options {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  flex: 1;
}

.upload-buttons {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.avatar-uploader {
  display: flex;
  justify-content: flex-start;
}

.avatar-url-input {
  width: 100%;
}

@media (max-width: 768px) {
  .avatar-upload-section {
    flex-direction: column;
    gap: 1rem;
    align-items: center;
  }
  
  .avatar-upload-options {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }
  
  .user-info {
    flex-direction: column;
    text-align: center;
  }
  
  .post-item {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }
  
  .post-actions {
    justify-content: center;
  }
}
</style>

